# 创建时间：2025-06-30
from fastapi import APIRouter, WebSocket
import cv2
import numpy as np
from app.services.image_processor import ImageProcessor
import json
import os

router = APIRouter()

@router.websocket('/ws/camera')
async def camera_ws(websocket: WebSocket):
    print('[ws/camera] 视频推流服务初始化成功，等待接收数据...')
    await websocket.accept()
    processor = ImageProcessor()  # 实例化图片处理对象
    import datetime
    try:
        take_photo_flag = False
        while True:
            msg = await websocket.receive()

            if msg['type'] == 'websocket.receive':
                if 'text' in msg:
                    # 处理文本消息
                    req = json.loads(msg['text'])
                    req_log = {k: v for k, v in req.items() if k != 'image'}
                    print(f'[ws/camera] 收到JSON请求: {req_log}')
                    if req.get('type') == 'takePhoto':
                        take_photo_flag = True
                        await websocket.send_text('收到拍照请求，下一帧将保存')
                    else:
                        await websocket.send_text('不支持的消息格式')
                elif 'bytes' in msg:
                    # 处理二进制消息
                    data = msg['bytes']
                    nparr = np.frombuffer(data, np.uint8)
                    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
                    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    if img is not None:
                        print(f'[{now}] 收到一帧，数据长度: {len(data)}，分辨率: {img.shape[1]}x{img.shape[0]}')
                        if take_photo_flag:
                            save_dir = 'saved_photos'
                            os.makedirs(save_dir, exist_ok=True)
                            filename = f"photo_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S_%f')}.jpg"
                            cv2.imwrite(os.path.join(save_dir, filename), img)
                            await websocket.send_text(f'拍照已保存: {filename}')
                            take_photo_flag = False
                        # 这里是主要逻辑，暂时注释掉
                        #else:
                        #    result = processor.process(data)
                        #    await websocket.send_text(result)
                    else:
                        print(f'[{now}] 收到一帧，数据长度: {len(data)}，解码失败')
                        await websocket.send_text('图片解码失败')
            else:
                print('收到非 websocket.receive 类型消息:', msg)
    except Exception as e:
        print('WebSocket关闭:', e)
    finally:
        await websocket.close()
